#pragma once
#include <rapidjson/document.h>
#include <yaml-cpp/yaml.h>
#include <unordered_map>
#include <map>
#include <string>
#include <atomic>
#include <thread>

#include "ws_connection.h"
#include "config.h"
#include "def.h"
#include "shm_utils.h"
#include "https_connection.h"
#include "https_connection_pool.h"
#include "exchange.h"


enum class LIGHTER_ORDER_TYPE : uint8_t {
    LimitOrder = 0,
    MarketOrder = 1,
    StopLossOrder = 2,
    StopLossLimitOrder = 3,
    TakeProfitOrder = 4,
    TakeProfitLimitOrder = 5,
    TWAPOrder = 6,
    TWAPSubOrder = 7,
    LiquidationOrder = 8,
};

enum class LIGHTER_TIME_IN_FORCE : uint8_t {
    ImmediateOrCancel = 0,
    GoodTillTime = 1,
    PostOnly = 2,
};

struct LighterAccountInfo {
    std::string api_key_private_key;
    int account_index;
    int api_key_index;
    long long int nonce;
};

class LighterClient : public std::enable_shared_from_this<LighterClient> {
public:
    explicit LighterClient(const std::string& config_path,
                           MARKETStruct* marketShmPtr,
                           boost::asio::io_context& ioc,
                           boost::asio::ssl::context& ssl_ctx);
    ~LighterClient();
    void run();
    void close();

private:
    void subscribeMarkets();
    void subscribeTrades();
    void handleMarketMessage(const std::string& msg);
    void handleTradeMessage(const std::string& msg);
    void handleOrderBookInit(int market_id, const rapidjson::Document& doc);
    void handleOrderBookUpdate(int market_id, const rapidjson::Document& doc);
    void handleAccountUpdateTrades(const rapidjson::Document& doc);
    void handleOrdersResponse(const rapidjson::Document& doc);
    void printOrderBooks() const;
    //下单
    void quantLoop();
    long long int getNextNonce();
    
private:
    //restful api
    std::shared_ptr<WSConnection> mdConn_;
    std::shared_ptr<WSConnection> tdConn_;
    //行情推送
    std::shared_ptr<HttpsConnectionPool> httpsConnPool_;
    // lighter交易所的配置信息
    LighterConfig config_;
    std::string config_path_;

    // 账户信息
    LighterAccountInfo accountInfo_;
    // 共享内存指针
    MARKETStruct* marketShmPtr_;

    // 本地维护的订单簿深度 
    int orderbook_depth_;
    // 本地维护的 OrderBook 
    std::unordered_map<int, OrderBook> orderBooks_;

    //下单线程变量
    std::thread quantThread_;
    bool stopQuantThread_ = false;



    // 连接参数
    std::string host_;
    std::string port_;
};
